<?php

namespace app\service;

use AlibabaCloud\Client\Exception\ClientException;

class OssFileService
{
    public static ?OssFileService $_instance = null;

    /**
     * @return OssFileService|mixed
     */
    public static function instance(): ?OssFileService
    {
        if (!static::$_instance) static::$_instance = new self();
        return static::$_instance;
    }

    /**
     * @throws ClientException
     */
    public function deleteOssFile(bool $is_vip = false): bool
    {
        switch ($is_vip) {
            case true:
                $_where['date_v'] = ['$lt' => date('Y-m-d', strtotime('-30 days'))];
                $_where['vip']    = 1;
                $limit            = 15;
                break;
            default:
                $_where['date_v'] = ['$lt' => date('Y-m-d', strtotime('-7 days'))];
                $_where['vip']    = ['$ne' => 1];
                $limit            = 20;
                break;
        }
        $list = MongodbService::instance()->initDb()->_select($_where, ['create_time', 'asc'], 1, $limit);
        if (empty($list)) return false;
        $objects_array = [];
        foreach ($list as $detail) {
            if (!empty($detail['files'])) {
                $objects1 = $objects2 = $objects3 = [];
                foreach ($detail['files'] as $value) {
                    $objects1[] = $value;
                }
                if (!empty($detail['completed_files'])) {
                    foreach ($detail['completed_files'] as $value) {
                        $objects2[] = $value['name'];
                        $objects3[] = $value['preview'] ?? [];
                    }
                }
                $objects                               = array_merge($objects1, $objects2, $objects3);
                $objects                               = array_filter($objects);
                $objects_array[(string)$detail['_id']] = $objects;
            }
        }
        if ($objects_array) {
            $token = OssService::instance()->stsToken();
            foreach ($objects_array as $_id => $value) {
                MongodbService::instance()->initDb()->_delete(['_id' => $_id]);
                OssService::instance()->deleteSignObject($token['Credentials'], $value);
            }
        }
        return true;
    }
}